<template>
  <div style="position: relative">

    <div
      class="over_box"
      v-show="userInfo.game_over"
    >
      <img
        class="over_bg"
        src="../assets/images/bg.jpg"
        alt=""
      >
      <img
        class="win"
        src="../assets/images/win.png"
        alt=""
      >
      <div class="score">
        <div class="text">您的成绩是：</div>
        <div class="result">{{time_text}}</div>
      </div>
      <img
        class="again"
        src="../assets/images/again.png"
        alt=""
        @click="again"
      >
      <div class="btn_bottom">
        <img
          src="../assets/images/guide_btn.png"
          alt=""
          @click="guide"
        >
        <img
          src="../assets/images/out.png"
          alt=""
          @click="out"
        >
      </div>
    </div>
    <div id="game-box">

    </div>

  </div>
</template>

<script lang="ts" setup>
import { defineComponent, ref, reactive, onMounted } from 'vue'
import loading_bg from '../assets/images/loading_bg.jpg'
import loading_title from '../assets/images/loading_title.png'
import loading_man from '../assets/images/loading_man.png'
import loading_grass from '../assets/images/loading_grass.png'
import progress from '../assets/images/progress.png'
import background from '../assets/images/background.jpg'

import guide_box from '../assets/images/guide_box.png'
import guideimg from '../assets/images/guide.png'

import d1 from '../assets/images/1.png'
import d2 from '../assets/images/2.png'
import d3 from '../assets/images/3.png'

import start from '../assets/images/start.png'
import mask from '../assets/images/mask.png'
import voice from '../assets/images/voice.png'
//import player from '../assets/images/player.png'
import clock from '../assets/images/clock.png'
import hand from '../assets/images/hand.png'
import heart from '../assets/images/heart.png'
import box from '../assets/images/box.png'
import rain from '../assets/images/rain.png'
import stone from '../assets/images/stone.png'
import manhole from '../assets/images/manhole.png'
import handshake from '../assets/images/handshake.png'
import djs from '../assets/images/djs.png'
import player from '../assets/images/货车.png'
// import clock from '../assets/images/clock.png'
// import hand from '../assets/images/hand.png'
// import heart from '../assets/images/爱心.png'
// import box from '../assets/images/箱子.png'
// import rain from '../assets/images/雨水.png'
// import stone from '../assets/images/石头.png'
// import manhole from '../assets/images/下水道.png'
// import handshake from '../assets/images/握手.png'

import bgmmusic from '../assets/audio/bgm.mp3'
import click from '../assets/audio/button.mp3'
import lose from '../assets/audio/lose.mp3'
import bound from '../assets/images/bound.png'
import axios from 'axios'

import { Toast, Popup } from 'vant'

// export default defineComponent({
//   name: 'Home',
// })
let game: any,
  bgm: any,
  clickbgm: any,
  losebgm: any,
  c: any,
  start_x: any,
  start_y: any

const game_start = ref<boolean>(false)
let game_over = ref<boolean>(false)
const time_text = ref<string>('')
const musicPause = ref<any>('play')
const userInfo = reactive({
  integralCosts: 0,
  playNumber: 0,
  game_over: false,
})

onMounted(() => {
  if (window.localStorage.getItem('musicPause')) {
    musicPause.value = window.localStorage.getItem('musicPause')
  } else {
    window.localStorage.setItem('musicPause', 'play')
  }
  getNums()
  setTimeout(() => {
    //模拟请求
    canvas_creat()
  }, 1000)
})

const getNums = () => {
  axios
    .post('http://wd.szbiu.com/api/test', {
      ticket: '1111111',
    })
    .then(function (res) {
      console.log(res)
    })
}

const again = () => {
  userInfo.game_over = false
  game.state.start('tips')
}

const guide = () => {}
const out = () => {}

const canPlay = (callback: any) => {
  setTimeout(() => {
    callback()
  }, 1000)
}
const gameDuration = () => {}
const canvas_creat = () => {
  // console.log(window.screen.availHeight,document.body.clientHeight,window.devicePixelRatio);
  let dw = window.devicePixelRatio === 2 ? 3 : window.devicePixelRatio

  var _width = window.screen.availWidth * dw
  var _height = document.body.clientHeight * dw
  let gd = document.getElementById('game-box') as any
  gd.style.cssText = `width:${document.body.clientWidth}px;height:${document.body.clientHeight}px;margin:0`
  //var dheight = window.screen.availHeight - document.documentElement.clientHeight;
  var unit = 1080 / _width
  game = new Phaser.Game({
    width: _width,
    height: _height,
    renderer: Phaser.CANVAS,
    parent: 'game-box',
    // "resolution": window.devicePixelRatio,
    transparent: true,
  })

  game.States = {}
  // 游戏初始化场景
  game.States.bootState = function () {
    this.init = function () {
      game.scale.pagesAlignHorizontally = true
      game.scale.pageAlignVertically = true
      game.scale.scaleMode = Phaser.ScaleManager.EXACT_FIT
      //失去焦点是否继续游戏
      game.stage.disableVisibilityChange = true
      //开启鼠标事件
      game.input.touch.capture = true
      game.scale.forcePortrait = true
      game.scale.refresh()
    }
    this.preload = function () {
      game.load.image('loading_bg', loading_bg)
      game.load.image('loading_title', loading_title)
      game.load.spritesheet('loading_man', loading_man, 163, 163, 8)
      game.load.image('loading_grass', loading_grass)
      game.load.image('progress', progress)
    }
    this.create = function () {
      game.state.start('loader')
    }
  }
  //游戏加载场景
  game.States.loaderState = function () {
    this.init = function () {
      this.stage.backgroundColor = '#caecaf'
      this.loading_bg = game.add.sprite(0, 0, 'loading_bg')
      this.loading_bg.width = game.width
      this.loading_bg.height = game.height
      this.loading_title = game.add.sprite(
        game.width / 2,
        200 / unit,
        'loading_title'
      )
      this.loading_title.anchor.set(0.5, 0.5)
      this.loading_title.width = 832 / unit
      this.loading_title.height = 232 / unit
    }
    this.preload = function () {
      //进度条
      // this.loading_man = game.add.sprite(
      //   game.width / 2,
      //   game.height / 2.2 - 99 / unit,
      //   'loading_man'
      // )
      // this.loading_man.animations.add('move')
      // this.loading_man.animations.play('move', 18, true)
      // this.loading_man.anchor.set(0.5, 0.5)
      // this.loading_man.width = 163 / unit
      // this.loading_man.height = 163 / unit
      // this.loading_man.scale.set(unit);

      this.progress = game.add.sprite(
        game.width / 2,
        game.height / 2.2,
        'loading_grass'
      )
      this.progress.anchor.set(0.5, 0.5)
      this.progress.width = 861 / unit
      this.progress.height = 58 / unit
      this.progressBar = game.add.sprite(
        124 / unit,
        game.height / 2.2,
        'progress'
      )
      this.progressBar.anchor.set(0, 0.5)
      this.progressBar.width = 835 / unit
      this.progressBar.height = 32 / unit

      this.cropRect = new Phaser.Rectangle(0, 0, 0, this.progressBar.height)
      this.tween = game.add
        .tween(this.cropRect)
        .to(
          { width: this.progressBar.width },
          800,
          'Linear',
          false,
          0,
          0,
          false
        )
      this.progressBar.crop(this.cropRect)
      this.tween.start()
      this.load_finish = false

      //加载资源-开始页

      //加载资源-game
      game.load.image('background', background)
      game.load.image('mask', mask)
      game.load.image('guide_box', guide_box)
      game.load.spritesheet('guide', guideimg, 551, 319, 10)
      game.load.image('start', start)
      game.load.spritesheet('voice', voice, 105, 105, 2)
      game.load.image('player', player)
      game.load.spritesheet('djs', djs, 200, 200, 3)

      game.load.image('d1', d1)
      game.load.image('d2', d2)
      game.load.image('d3', d3)

      game.load.image('bound', bound)
      game.load.image('clock', clock)
      game.load.image('hand', hand)
      game.load.image('heart', heart)
      game.load.image('box', box)
      game.load.image('rain', rain)
      game.load.image('stone', stone)
      game.load.image('handshake', handshake)
      game.load.image('manhole', manhole)

      // //音频
      game.load.audio('bgm', bgmmusic, true)
      game.load.audio('click', click, true)
      game.load.audio('lose', lose, true)
      game.load.onLoadComplete.add(() => {
        console.log('加载完成')
        this.load_finish = true
        game.sound.setDecodedCallback(
          ['bgm', 'click'],
          function () {
            bgm = game.add.sound('bgm')
            setTimeout(function () {
              // game.state.start('tips')
            }, 1000)
          },
          this
        )
      })
    }
    this.update = function () {
      if (this.load_finish) {
        this.progressBar.updateCrop()
      }
    }
  }

  //倒计时
  game.States.tipsState = function () {
    this.init = function () {
      this.stage.backgroundColor = '#fff'
    }

    this.create = function () {
      console.log('倒计时!')
      this.bg = game.add.sprite(0, 0, 'background')
      this.bg.width = game.width
      this.bg.height = game.height

      this.djs = game.add.sprite(game.width / 2, game.height / 2, 'djs')
      let aim = this.djs.animations.add('move')
      this.djs.anchor.set(0.5)
      this.djs.width = (200 / unit) * 1.2
      this.djs.height = (200 / unit) * 1.2
      this.djs.animations.play('move', 1, false)

      //  this.djs.onStart.add(animationStarted, this);
      //  this.djs.onLoop.add(animationLooped, this);
      aim.onComplete.add(() => {
        game.state.start('game')
      }, this)
      // game.time.events.add(Phaser.Timer.SECOND * 1, function () {
      //   this.djs.destroy()
      // })

      // this.countdownImages = ['d1', 'd2', 'd3']
      // this.spriteGroup = game.add.group()
      // this.countdownText = this.spriteGroup.create(
      //   game.width / 2,
      //   game.height / 2,
      //   this.countdownImages[2]
      // )
      // this.countdownText2 = null
      // this.countdownText3 = null

      // 初始化时间
      this.timeLeft = 3
    }
    this.update = function () {
      // 每秒减少1秒（根据需要调整）
      // this.timeLeft -= 1 / 50
      // // 更新显示文本
      // if (Math.round(this.timeLeft) == 2) {
      //   this.countdownText.destroy()
      //   this.countdownText2 = this.spriteGroup.create(
      //     game.width / 2,
      //     game.height / 2,
      //     this.countdownImages[1]
      //   )
      // }
      // // 倒计时结束检测
      // if (Math.round(this.timeLeft) == 1) {
      //   this.countdownText2.destroy()
      //   this.countdownText3 = this.spriteGroup.create(
      //     game.width / 2,
      //     game.height / 2,
      //     this.countdownImages[0]
      //   )
      // }
      // if (Math.round(this.timeLeft) == 0) {
      //   game.state.start('game')
      // }
    }
  }

  game.States.mainState = function () {
    this.init = function () {
      this.stage.backgroundColor = '#fff'
    }
    this.create = function () {
      this.bg = game.add.sprite(0, 0, 'background')
      this.bg.width = game.width
      this.bg.height = game.height
      this.mask = game.add.sprite(0, 0, 'mask')
      this.mask.width = game.width
      this.mask.height = game.height

      this.guide_box = game.add.sprite(
        game.width / 2,
        game.height / 2 - 100 / unit,
        'guide_box'
      )
      this.guide_box.width = (714 / unit) * 1.2
      this.guide_box.height = (1122 / unit) * 1.2
      this.guide_box.anchor.set(0.5)

      this.guide_img = game.add.sprite(
        game.width / 2,
        game.height / 2 + 80 / unit,
        'guide'
      )
      this.guide_img.animations.add('move')
      this.guide_img.anchor.set(0.5)
      this.guide_img.width = (551 / unit) * 1.2
      this.guide_img.height = (319 / unit) * 1.2
      this.guide_img.animations.play('move', 10, true)

      this.start_btn = game.add.sprite(
        game.width / 3,
        game.height / 2 + this.guide_box.height / 2 - 280 / unit,
        'start'
      )
      this.start_btn.inputEnabled = true
      this.start_btn.anchor.set(0.5)
      this.start_btn.width = (557 / unit) * 0.6
      this.start_btn.height = (96 / unit) * 0.7
      this.start_btn.input.priorityID = 1

      //不在提示
      this.no_tips = game.add.sprite(
        game.width / 1.5,
        game.height / 2 + this.guide_box.height / 2 - 280 / unit,
        'start'
      )
      this.no_tips.inputEnabled = true
      this.no_tips.anchor.set(0.5)
      this.no_tips.width = (557 / unit) * 0.6
      this.no_tips.height = (96 / unit) * 0.7
      this.no_tips.input.priorityID = 2

      this.play_text = game.add.text(
        game.width / 2,
        game.height / 2 + this.guide_box.height / 2 - 170 / unit,
        `免费次数剩余${userInfo.playNumber}次\n次数消耗完后，需消耗${userInfo.integralCosts}积分继续游戏`,
        { font: ' 38px Arial', fill: '#fff', align: 'center' }
      )
      this.play_text.anchor.set(0.5)

      if (musicPause.value === 'play') {
        bgm.play()
      } else {
        bgm.pause()
      }

      this.voiceBtn = game.add.sprite(
        game.width - 105 / unit - 50,
        115 / unit,
        'voice',
        musicPause.value === 'play' ? 0 : 1
      )
      this.voiceBtn.width = 105 / unit
      this.voiceBtn.height = 105 / unit
      this.voiceBtn.inputEnabled = true
      this.voiceBtn.events.onInputDown.add(() => {
        if (musicPause.value === 'play') {
          musicPause.value = 'pause'
          window.localStorage.setItem('musicPause', 'pause')
          this.voiceBtn.frame = 1
          bgm.stop()
        } else {
          musicPause.value = 'play'
          window.localStorage.setItem('musicPause', 'play')
          this.voiceBtn.frame = 0
          bgm.play()
        }
      }, this)

      clickbgm = game.add.audio('click', 0.5, false)

      this.start_btn.events.onInputDown.add(() => {
        if (musicPause.value === 'play') {
          clickbgm.play()
          game.state.start('tips')
        }

        canPlay(function () {})
      }, this)
    }
  }

  game.States.gameState = function () {
    this.init = function () {
      this.stage.backgroundColor = '#fff'
      losebgm = game.add.audio('lose', 0.2, false)
    }
    this.create = function () {
      // 物理系统
      // 背景

      //箱子(直接+20m)
      //握手(5秒内画面不显示障碍物如有则消失)
      //爱心(5秒内无障碍，且加速)
      //雨水-行驶速度加快
      //石头一第一次碰到-30m，第二次碰到游戏结束结算分数
      //没井盖的下水道-碰到直接游戏结束，结算分数

      this.start = true
      game_start.value = true
      this.lose = 0
      this.meter = 0
      this.speed_specialEffectStatus = false //加速特效
      this.speed_specialEffectTime = 0
      this.obstacle_clear = false //无障碍
      this.collisionStoneNum = 0 //碰撞石头次数
      this.config_data = {
        common_velocity: 600, //物体下落速度
        bgSpeed: 500, //背景速度
        playerShowTime: 1500, //玩家出现时间
        player_position: game.height - 150,
        XArr: [180 / unit, game.width - 180 / unit], //左右边界区间
        boxSetY: -50,
        handshakeSetY: -200,
        heartSetY: -350,
        stoneSetY: -500,
        manholeSetY: -650,
        rainSetY: -800,

        meterSpeed: 1, //计分速度，默认1秒一米,
      }
      //console.log(game.width, game.height)
      // game.world.setBounds(200 / unit, 0, game.width - 200 / unit, game.height)
      game.world.setBounds(
        0,
        -game.height,
        game.width,
        game.height + game.height
      )
      game.physics.startSystem(Phaser.Physics.ARCADE)
      this.bg = game.add.tileSprite(0, 0, game.width, game.height, 'background')
      this.bg.tileScale.x = game.width / 1080
      this.bg.tileScale.y = game.width / 1080
      this.bg.autoScroll(0, 500)
      this.bg.fixedToCamera = true
      //制作边界，左边界和有边界
      this.bounds = game.add.group()
      this.bounds.enableBody = true
      this.bounds.fixedToCamera = true
      this.left_bound = this.bounds.create(0, 0, 'bound')
      this.left_bound.width = 180 / unit
      this.left_bound.height = game.height
      this.left_bound.body.immovable = true

      console.log(game.width, this.left_bound.width)
      this.right_bound = this.bounds.create(game.width - 180 / unit, 0, 'bound')
      this.right_bound.width = 180 / unit
      this.right_bound.height = game.height
      this.right_bound.body.immovable = true
      this.voiceBtn = game.add.sprite(
        game.width - 105 / unit - 50,
        115 / unit,
        'voice',
        musicPause.value === 'play' ? 0 : 1
      )
      this.voiceBtn.width = 105 / unit
      this.voiceBtn.height = 105 / unit
      this.voiceBtn.inputEnabled = true
      this.voiceBtn.events.onInputDown.add(() => {
        if (musicPause.value === 'play') {
          musicPause.value = 'pause'
          window.localStorage.setItem('musicPause', 'pause')
          this.voiceBtn.frame = 1
          bgm.stop()
        } else {
          musicPause.value = 'play'
          window.localStorage.setItem('musicPause', 'play')
          this.voiceBtn.frame = 0
          bgm.play()
        }
      }, this)

      //创建箱子组-特效加米数
      this.boxs = game.add.group()
      this.boxs.enableBody = true
      this.boxs.createMultiple(5, 'box')
      this.boxs.setAll('outOfBoundsKill', true)
      this.boxs.setAll('checkWorldBounds', true)
      this.boxs.forEach((box: any) => {
        //box.scale.set(unit * 1.5)
        //box.anchor.set(0.5, 0.5)
      }, this)

      //创建爱心组-特效全清除且加速
      this.hearts = game.add.group()
      this.hearts.enableBody = true
      this.hearts.createMultiple(3, 'heart')
      this.hearts.setAll('outOfBoundsKill', true)
      this.hearts.setAll('checkWorldBounds', true)
      this.hearts.forEach((heart: any) => {
        //  heart.scale.set(unit * 1.5)
        // heart.anchor.set(0.5, 0.5)
      }, this)

      //创建石头组-特效第一次减少30m，第二次游戏结束
      this.stones = game.add.group()
      this.stones.enableBody = true
      this.stones.createMultiple(3, 'stone')
      this.stones.setAll('outOfBoundsKill', true)
      this.stones.setAll('checkWorldBounds', true)
      this.stones.forEach((stone: any) => {
        // stone.scale.set(unit * 1.5)
        // stone.anchor.set(0.5, 0.5)
      }, this)

      //创建握手组,特效全部清除障碍
      this.handshakes = game.add.group()
      this.handshakes.enableBody = true
      this.handshakes.createMultiple(5, 'handshake')
      this.handshakes.setAll('outOfBoundsKill', true)
      this.handshakes.setAll('checkWorldBounds', true)
      this.handshakes.forEach((handshake: any) => {
        //handshake.scale.set(unit * 1.5)
        //handshake.anchor.set(0.5, 0.5)
      }, this)

      //创建雨水组,特效游戏开始变得加快，速度加快
      this.rains = game.add.group()
      this.rains.enableBody = true
      this.rains.createMultiple(3, 'rain')
      this.rains.setAll('outOfBoundsKill', true)
      this.rains.setAll('checkWorldBounds', true)
      this.rains.forEach((rain: any) => {
        //rain.scale.set(unit * 1.5)
        //rain.anchor.set(0.5, 0.5)
      }, this)

      //创建井盖组，效果是游戏直接结束
      this.manholes = game.add.group()
      this.manholes.enableBody = true
      this.manholes.createMultiple(3, 'manhole')
      this.manholes.setAll('outOfBoundsKill', true)
      this.manholes.setAll('checkWorldBounds', true)
      this.manholes.forEach((manhole: any) => {
        //manhole.scale.set(unit * 1.5)
        //manhole.anchor.set(0.5, 0.5)
      }, this)

      this.player = game.add.sprite(
        game.width / 2,
        this.config_data.player_position,
        'player'
      )
      game.physics.arcade.enable(this.player)
      this.player.animations.add('move')
      this.player.animations.play('move', 6, true)
      this.player.anchor.set(0.5, 0.5)
      this.player.scale.set(unit * 1)

      this.player.body.collideWorldBounds = true
      this.player.body.allowGravity = false
      this.player.body.gravity.y = 0
      this.player.body.bounce.y = 0.2
      this.player.body.velocity.y = 0
      this.player.inputEnabled = true
      this.player.input.enableDrag()

      this.hand = game.add.sprite(
        game.width / 2 + 50,
        this.config_data.player_position,
        'hand'
      )
      this.addobstacle()

      this.hand.anchor.set(0.5, 0.5)
      this.hand.scale.set(unit * 1.5)
      this.player.inputEnabled = true
      this.hand_t = game.add
        .tween(this.hand)
        .to({ alpha: 0 }, 200, 'Linear', true, 0, -1, true)

      this.text = game.add.text(
        game.width / 2 + 70 / unit,
        80 / unit,
        this.meter + '米',
        { font: '72px Arial', fill: '#000', align: 'center' }
      )
      this.text.anchor.set(0.5)
      game.time.events.loop(Phaser.Timer.SECOND * 1, this.updateText, this)
    }

    this.updateText = function () {
      if (this.start) {
        this.meter = this.meter + this.config_data.meterSpeed
        if (this.meter) {
          this.hand_t.pause()
        }
        this.text.setText(
          this.meter + '米' + ':特效时间' + this.speed_specialEffectTime + '秒'
        )
      }
    }
    // 产生箱子
    this.generatebox = function () {
      let box = this.boxs.getFirstExists(false)
      if (box) {
        let randArr = this.randXArr()
        box.reset(randArr[0], this.config_data.boxSetY) //
        box.body.velocity.y = this.config_data.common_velocity
      }
    }
    // 产生爱心
    this.generateheart = function () {
      if (this.obstacle_clear) return false //无障碍的时候不产生
      let heart = this.hearts.getFirstExists(false)
      if (heart) {
        let randArr = this.randXArr()
        heart.reset(randArr[0], this.config_data.heartSetY) //增加
        heart.body.velocity.y = this.config_data.common_velocity
      }
    }
    //产生石头
    this.generatestone = function () {
      if (this.obstacle_clear) return false //无障碍的时候不产生
      let stone = this.stones.getFirstExists(false)
      if (stone) {
        let randArr = this.randXArr()
        stone.reset(randArr[0], this.config_data.stoneSetY) //增加
        stone.body.velocity.y = this.config_data.common_velocity
      }
    }

    //产生握手
    this.generatehandshake = function () {
      if (this.obstacle_clear) return false //无障碍的时候不产生
      let handshake = this.handshakes.getFirstExists(false)
      if (handshake) {
        let randArr = this.randXArr()
        handshake.reset(randArr[0], this.config_data.handshakeSetY) //增加
        handshake.body.velocity.y = this.config_data.common_velocity
      }
    }

    //产生雨水
    this.generaterain = function () {
      if (this.obstacle_clear) return false //无障碍的时候不产生
      let rain = this.rains.getFirstExists(false)
      if (rain) {
        let randArr = this.randXArr()
        rain.reset(randArr[0], this.config_data.rainSetY) //增加
        rain.body.velocity.y = this.config_data.common_velocity
      }
    }

    //产生井盖
    this.generatemanhole = function () {
      if (this.obstacle_clear) return false //无障碍的时候不产生
      let manhole = this.manholes.getFirstExists(false)
      if (manhole) {
        let randArr = this.randXArr()
        manhole.reset(randArr[0], this.config_data.manholeSetY) //增加
        manhole.body.velocity.y = this.config_data.common_velocity
      }
    }

    //统一加障碍跟福利
    this.addobstacle = function () {
      //每10秒执行产生爱心
      this.heartTimer = game.time.events.loop(
        Phaser.Timer.SECOND * 100,
        this.generateheart,
        this
      )
      //每3秒执行产生石块
      this.stoneTimer = game.time.events.loop(
        Phaser.Timer.SECOND * 6,
        this.generatestone,
        this
      )
      //每2秒执行产生箱子
      this.boxTimer = game.time.events.loop(
        Phaser.Timer.SECOND * 2,
        this.generatebox,
        this
      )
      //每8秒执行产生握手
      this.handshakeTimer = game.time.events.loop(
        Phaser.Timer.SECOND * 7,
        this.generatehandshake,
        this
      )
      //每5秒执行产生雨水
      this.rainTimer = game.time.events.loop(
        Phaser.Timer.SECOND * 50,
        this.generaterain,
        this
      )

      //每10秒执行产生井盖
      this.manholeTimer = game.time.events.loop(
        Phaser.Timer.SECOND * 100,
        this.generatemanhole,
        this
      )
    }

    //随机三组跑道左右间隔
    this.randXArr = function () {
      //第一组
      let trackWidth = game.width - 360 / unit
      let trackItemWidth = trackWidth / 3
      let arr1 = [180 / unit, trackItemWidth + 180 / unit]
      let arr2 = [trackItemWidth + 180 / unit, trackItemWidth * 2 + 180 / unit]
      let arr3 = [
        trackItemWidth * 2 + 180 / unit,
        trackItemWidth * 3 + 180 / unit,
      ]
      let rand = Math.floor(Math.random() * 3)
      if (rand == 0) {
        return arr1
      }
      if (rand == 1) {
        return arr2
      }
      if (rand == 2) {
        return arr3
      }
    }

    //消除所有障碍物
    this.clearObstacle = function () {
      let arr = ['boxs', 'hearts', 'stones', 'handshakes', 'rains', 'manholes']
      arr.forEach((item: any) => {
        this[item].forEach(function (item: any) {
          item.kill()
        })
      })
    }

    //统一消除定时器
    this.removeobstacle = function () {
      let arr = [
        'boxTimer',
        'heartTimer',
        'stoneTimer',
        'handshakeTimer',
        'rainTimer',
        'manholeTimer',
      ]
      arr.forEach((item: any) => {
        game.time.events.remove(this[item])
      })
    }

    //游戏结束
    this.gameOver = function () {
      this.start = false
      this.player.inputEnabled = false
      this.player.body.velocity.y = 0
      game.add.tween(player).to({ alpha: 0 }, 50, 'Linear', true, 0, -1, true)
      this.bg.autoScroll(0, 0)
      this.removeobstacle()
      userInfo.game_over = true
    }

    /*
    特殊效果
      特殊效果
      特殊效果
      特殊效果
      特殊效果
      特殊效果
      特殊效果
      特殊效果
    */

    //五秒加速，且没有障碍物体
    this.generateEffect = function (str) {
      if (str == 'box') {
        this.meter += 20
      } else if (str == 'heart') {
        //爱心 加速
        this.speed_specialEffectStatus = true
        this.obstacle_clear = true
        this.record_bgSpeed = this.config_data.bgSpeed //记录吃到爱心时候的速度
        this.config_data.bgSpeed = this.config_data.bgSpeed * 3
        this.bg.autoScroll(0, this.config_data.bgSpeed)
        this.record_common_velocity = this.config_data.common_velocity //记录吃到爱心时候的速度
        this.config_data.common_velocity = this.config_data.common_velocity * 3

        this.record_meterSpeed = this.config_data.meterSpeed //记录吃到爱心时候的速度
        this.config_data.meterSpeed = this.config_data.meterSpeed * 5
        this.speed_specialEffectTime = 0

        this.heartEffectTimer = game.time.events.loop(
          Phaser.Timer.SECOND * 1,
          () => {
            if (
              this.speed_specialEffectStatus &&
              this.speed_specialEffectTime < 5
            ) {
              this.speed_specialEffectTime++
            } else {
              this.speed_specialEffectStatus = false
              this.speed_specialEffectTime = 0
              this.config_data.bgSpeed = this.record_bgSpeed
              this.bg.autoScroll(0, this.config_data.bgSpeed)
              this.config_data.common_velocity = this.record_common_velocity
              this.config_data.meterSpeed = this.record_meterSpeed
              this.obstacle_clear = false
              game.time.events.remove(this.heartEffectTimer)
              // this.addobstacle()
            }
          },
          this
        )
      } else if (str == 'stone') {
        if (this.collisionStoneNum === 0) {
          this.collisionStoneNum = 1
          this.meter = this.meter - 30
        } else {
          this.collisionStoneNum = 0
          this.gameOver()
        }
      } else if (str == 'manhole') {
        this.gameOver()
      } else if (str == 'handshake') {
        this.obstacle_clear = true
        this.speed_specialEffectTime = 0
        this.handshakeEffectTimer = game.time.events.loop(
          Phaser.Timer.SECOND * 1,
          () => {
            if (
              this.speed_specialEffectStatus &&
              this.speed_specialEffectTime < 5
            ) {
              this.speed_specialEffectTime++
            } else {
              this.speed_specialEffectStatus = false
              this.speed_specialEffectTime = 0
              this.obstacle_clear = false
              game.time.events.remove(this.handshakeEffectTimer)
            }
          },
          this
        )
      } else if (str == 'rain') {
        this.config_data.bgSpeed = this.config_data.bgSpeed * 3
        this.config_data.common_velocity = this.config_data.common_velocity * 3
        this.config_data.meterSpeed = this.config_data.meterSpeed * 3
        this.bg.autoScroll(0, this.config_data.bgSpeed)
        let arr = [
          'boxs',
          'hearts',
          'stones',
          'handshakes',
          'rains',
          'manholes',
        ]
        arr.forEach((item: any) => {
          this[item].forEach((item: any) => {
            item.body.velocity.y = this.config_data.common_velocity
          })
        })
      }
    }

    /*
    主函数刷新渲染区
     主函数刷新渲染区
      主函数刷新渲染区
       主函数刷新渲染区
    */

    this.update = function () {
      this.player.y = this.config_data.player_position
      game.physics.arcade.collide(this.player, this.bounds, () => {
        if (this.player.x < 180 / unit) {
          this.player.x = 180 / unit
        }
        if (this.player.x > game.width - 180 / unit) {
          this.player.x = game.width - 180 / unit
        }
      })

      //所有障碍物清除
      if (this.obstacle_clear) {
        this.clearObstacle()
      }

      //加20m
      game.physics.arcade.overlap(
        this.boxs,
        this.player,
        (player: any, box: any) => {
          try {
            box.kill()
            this.generateEffect('box')
          } catch (err) {}
        },
        null,
        this
      )

      //加速五秒
      game.physics.arcade.overlap(
        this.hearts,
        this.player,
        (player: any, heart: any) => {
          try {
            heart.kill()
            this.generateEffect('heart')
          } catch (err) {}
        },
        null,
        this
      )

      //石头碰撞
      game.physics.arcade.overlap(
        this.stones,
        this.player,
        (player: any, stone: any) => {
          try {
            stone.kill()
            this.generateEffect('stone')
          } catch (err) {}
        },
        null,
        this
      )

      //握手碰撞
      game.physics.arcade.overlap(
        this.handshakes,
        this.player,
        (player: any, handshake: any) => {
          try {
            handshake.kill()
            this.generateEffect('handshake')
          } catch (err) {}
        },
        null,
        this
      )

      //雨水碰撞
      game.physics.arcade.overlap(
        this.rains,
        this.player,
        (player: any, rain: any) => {
          try {
            rain.kill()
            this.generateEffect('rain')
          } catch (err) {}
        },
        null,
        this
      )

      //井盖碰撞
      game.physics.arcade.overlap(
        this.manholes,
        this.player,
        (player: any, manhole: any) => {
          try {
            manhole.kill()
            this.generateEffect('manhole')
          } catch (err) {}
        },
        null,
        this
      )
    }
  }

  game.state.add('boot', game.States.bootState)
  game.state.add('loader', game.States.loaderState)
  game.state.add('main', game.States.mainState)
  game.state.add('game', game.States.gameState)
  game.state.add('tips', game.States.tipsState)
  game.state.start('boot')
}
</script>

<style scoped>
.tip_box {
  position: relative;
  width: 18rem;
  height: 24rem;
}
.tip {
  position: absolute;
  width: 16rem;
  height: 20rem;
  margin: 0 auto;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  display: block;
}
.sure {
  position: absolute;
  width: 6rem;
  margin: 0 auto;
  top: 20rem;
  left: 50%;
  transform: translateX(-50%);
  display: block;
}
.clock {
  text-align: center;
  color: #fff;
  font-size: 24px;
  width: 100%;
  position: absolute;
  top: 20px;
  left: 0;
  vertical-align: middle;
  box-sizing: border-box;
  pointer-events: none;
}
.clock span {
  display: inline-block;
  background: url('../assets/images/clock.png') no-repeat;
  background-size: 100% 100%;
  width: 32px;
  height: 32px;
  vertical-align: middle;
  box-sizing: border-box;
  -webkit-touch-callout: none;
  -moz-user-select: none; /*火狐*/
  -webkit-user-select: none; /*webkit浏览器*/
  -ms-user-select: none; /*IE10*/
  -khtml-user-select: none; /*早期浏览器*/
  user-select: none;
  pointer-events: none;
}
.clock i {
  display: inline-block;
  -webkit-touch-callout: none;
  -moz-user-select: none; /*火狐*/
  -webkit-user-select: none; /*webkit浏览器*/
  -ms-user-select: none; /*IE10*/
  -khtml-user-select: none; /*早期浏览器*/
  user-select: none;
  font-style: normal;
  pointer-events: none;
}
.over_box {
  width: 100vw;
  height: 100vh;
  position: relative;
  z-index: 9999;
}
.over_bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
}
.win {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: 5rem;
  width: 15rem;
}
.score {
  position: absolute;
  width: 100%;
  top: 19rem;
  left: 0;
  text-align: center;
}
.result {
  font-size: 2rem;
  color: #d32f2f;
  font-weight: bold;
}
* {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-tap-highlight-color: transparent;
}

.again {
  position: absolute;
  width: 15rem;
  height: 2.25rem;
  transform: translateX(-50%);
  top: 25rem;
  left: 50%;
}
.btn_bottom {
  position: absolute;
  width: 15rem;
  transform: translateX(-50%);
  top: 29rem;
  left: 50%;
  display: flex;
  justify-content: center;
}
.btn_bottom img {
  width: 7rem;
  height: 2rem;
  margin: 0 0.5rem;
}
</style>
